package br.ufal.tci.nexos.arcolive;

import br.ufal.tci.nexos.arcolive.exception.ArCoLIVEPersistenceException;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipant;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistence;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistenceConnectionPoll;

public class ArCoLIVESecurityManager {

	private ArCoLIVEPersistenceConnectionPoll pcp;
	private static ArCoLIVESecurityManager singleton;
	ArCoLIVEPersistence persistence;
	
	private ArCoLIVESecurityManager() throws ArCoLIVEPersistenceException {
		this.pcp = ArCoLIVEPersistenceConnectionPoll.getInstance();
	}
	
	public static ArCoLIVESecurityManager getInstance() throws ArCoLIVEPersistenceException {
		if (singleton == null) {
			singleton = new ArCoLIVESecurityManager();
		}
		return singleton;
	}
	
	public boolean checkPermission(int commandId, int serviceId, int instanceId, ArCoLIVEParticipant participant) {
		if (this.persistence == null) {
			try {
				this.persistence = pcp.getDatabaseConnection();
			} catch (ArCoLIVEPersistenceException e) {
				return false;
			}
		}
		boolean result = this.persistence.isCommandPermitted(commandId, participant, serviceId, instanceId);
		pcp.addDatabaseConnection(this.persistence);
		this.persistence = null;
		System.gc();
		return result;
	}
	
	public boolean checkPermission(int commandId, int serviceId, int instanceId, ArCoLIVEParticipant participant, ArCoLIVEPersistence persistence) {
		this.persistence = persistence;
		return persistence.isCommandPermitted(commandId, participant, serviceId, instanceId);
	}
	
}
